#!/bin/sh -eu
#
# Copyright (c) 2002-2006 FreeBSD GNOME Team <freebsd-gnome@FreeBSD.org>
# Copyright (c) 2012-2017 FreeBSD Xfce Team <xfce@FreeBSD.org>
# Copyright (c) 2020-2023 Olivier Duchateau <duchateau.olivier@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# Based on marcusmerge, adapted for the elementary OS desktop.
#


#### User settings

# Full path to this repository
LOCAL_REP=""

# The official ports collection
# https://docs.freebsd.org/en/books/handbook/ports/#ports-using
PORTSDIR="/usr/ports"

# Name of the branch (used in official ports collection)
BRANCH="main"
####

#### Don't change anything below
PRGFILE=$(realpath "$0")
PRGNAME="${0##*/}"

# We follow upstream releases
ELEMENTARY_RELEASE="7.0"

CWD=$(pwd)

# Repository
HOST="https://codeberg.org/olivierd/freebsd-ports-elementary.git"


err()
{
    echo "$@" >&2
    exit 1
}

usage()
{
    cat <<EOF >&2
usage: $PRGNAME option

options:
  -h    show this help
  -c    clone remote repository
  -m    merge into the official ports tree
  -u    update local repository
  -r    revert changes in official ports tree
EOF
    exit 0
}

check_git()
{
    if [ -x $(which git 2>/dev/null) ]; then
        echo $(which git);
    else
        err "ERROR: git(1) not found. Try 'pkg install git'";
    fi
}

init_repository()
{
    if [ ! -d "${LOCAL_REP}" ]; then
        mkdir -p ${LOCAL_REP}
    fi
}

update()
{
    cd ${LOCAL_REP}

    # Check current branch
    CURRENT_BRANCH=$(${1} branch --show-current)
    if [ "${CURRENT_BRANCH}" = "${2}" ]; then
        ${1} pull
    else
        err "ERROR: mismatch branch!"
    fi
}

clone()
{
    GIT=$(check_git)

    if [ ! -d "${LOCAL_REP}/.git" ]; then
        $(init_repository)

        cd ${LOCAL_REP}
        ${GIT} clone -b ${ELEMENTARY_RELEASE} --depth 1 ${HOST} .
    else
        update ${GIT} ${ELEMENTARY_RELEASE};
    fi
    exit 0
}

revert()
{
    GIT=$(check_git)

    if [ ! -d "${LOCAL_REP}/.git" ]; then
        err "ERROR: you mut clone repository first!"
    else
        if [ -n "${PORTSDIR}" ]; then
            cd ${PORTSDIR};

            ${GIT} switch ${BRANCH};

            dirs=$(find ${LOCAL_REP} -type d -depth 2 \
                   ! -path '*/.git*' ! -path '*/Mk*');
            for d in ${dirs}; do
                # Name
                port=${d##${LOCAL_REP}/}

                if [ -d "${port}" ]; then
                    rm -Rf ${port};
                fi
            done

            if [ -e Mk/Uses/elementary.mk ]; then
                rm Mk/Uses/elementary.mk
            fi

            ${GIT} restore -s ${BRANCH} . ;

            ${GIT} branch -D elementary ;

            cd ${CWD};
            exit 0
       else
           err "ERROR: ${PORTSDIR} is not defined!"
       fi
    fi
}

merge()
{
    GIT=$(check_git)

    if [ ! -d "${LOCAL_REP}/.git" ]; then
        err "ERROR: you must clone repository first!";
    else
        if [ -n "${PORTSDIR}" ]; then
            cd ${PORTSDIR};
            ${GIT} switch elementary 2>/dev/null;
            if [ ${?} -ne 0 ]; then
                ${GIT} switch -c elementary;
            fi

            dirs=$(find ${LOCAL_REP} -type d -depth 2 \
                   ! -path '*/.git*' ! -path '*/Mk*');
            for d in ${dirs}; do
                # Name
                port=${d##${LOCAL_REP}/}

                # New port
                if [ ! -d "${port}" ]; then
                    mkdir "${port}";
                fi

                # Clean port directory
                if [ -d "${port}/work" ]; then
                    rm -Rf "${port}/work";
                fi

                # Overrides files/
                if [ -d "${port}/files" ]; then
                    rm -Rf "${port}/files";
                fi

                # Copy everything
                cp -Rv ${d}/* ${port};
            done

            # Mk/...
            if [ -e "${LOCAL_REP}/Mk/Uses/elementary.mk" ]; then
                cp ${LOCAL_REP}/Mk/Uses/elementary.mk ${PORTSDIR}/Mk/Uses ;
            fi

            cd ${CWD};
            exit 0
        else
            err "ERROR: ${PORTSDIR} is not defined!"
        fi
    fi
}

opts=$(getopt hcmur ${*})
if [ ${?} -ne 0 ]; then
    usage
fi
set -- ${opts}

if [ ${#} -eq 1 ]; then
    usage;
else
    while true; do
        case "${1}" in
            -h)
                usage;
                shift
                ;;
            -c)
                clone;
                shift
                ;;
            -m)
                merge;
                shift
                ;;
            -u)
                clone;
                shift
                ;;
            -r)
                revert;
                shift
                ;;
            --)
                shift ; break
                ;;
        esac
    done
fi
